<template>
  <view class="child-list">
    <view class="section-name">
      <view class="name" @click="unfold">
        <text>{{config.label||''}}</text>
        <text class="cu-load margin-left-xs" :class="loading?'loading':''"></text>
        <view class="unfold" v-if="config.unfold ===false">
          <text class="cuIcon-unfold"></text>
        </view>
      </view>

      <view class="to-more" v-if="config.unfold !==false">
        <picker @change="bindPickerChange" v-model="curTemplate" :range="templates">
          <button v-if="templateButtonLabel" class="button light  round border margin-right-xs"
            @click="changeTemplatePopup">{{templateButtonLabel}}</button>
        </picker>

        <button class="button light sm radius margin-left" v-show="disabled!==true"
          :class="{sm:publicButton.length>2,'bx-line-btn-color':theme}" v-for="(btn,index) in publicButton" :key="index"
          @click="onButton(btn)">
          <text class="text">{{btn.button_name||''}}</text></button>
      </view>
    </view>
    <view class="list-box" v-if="config.unfold !==false">
      <view class="list-item table-head">
        <view class="col-item selection" v-if="showSelection">
          <text class="cuIcon-squarecheckfill text-green" v-if="isSelectAll" @click="cancelSelectAll()"></text>
          <view class="half-checked" v-else-if="isHalfSelect" @click="selectAll()">
            <text class="checkbox__inner-icon"></text>
          </view>
          <text class="cuIcon-square" v-else @click="selectAll()"></text>
        </view>
        <view class="col-item" v-for="col in showColumn" :key="col.columns"
          :style="{'min-width':colMinWidth&&colMinWidth[col.columns]?colMinWidth[col.columns]:''}">
          <view class="col-item-contain">
            <view class="label"> {{col.label||''}}</view>
          </view>
          <field-explain :text="col.moreConfig.help_tips" :color="col.moreConfig.explainColor"
            v-if="col.moreConfig&&col.moreConfig.help_tips">
          </field-explain>
        </view>
        <text class="cuIcon-add  more-btn hidden" v-if="showHandle&&!disabled"></text>
        <text class="cuIcon-delete text-black hidden" v-if="showDelete&&!disabled"></text>
      </view>
      <view class="list-item" v-for="(item,index) in listData" v-show="item._dirtyFlags!=='delete'"
        @click="onButton({button_type:'edit'},index)">
        <view class="col-item selection" @click.stop="changeChecked(index,'listData')" v-if="showSelection">
          <text class="cuIcon-squarecheckfill text-green" v-if="listChecked&&listChecked.includes(index)"></text>
          <text class="cuIcon-square" v-else></text>
        </view>
        <view class="col-item" v-for="col in showColumn" :key="col.columns"
          :style="{'min-width':colMinWidth&&colMinWidth[col.columns]?colMinWidth[col.columns]:''}">
          <view v-if="inlineEditCols(col.columns,item)" @click.stop="" class="input-box">
            <uni-easyinput primaryColor="#38C09E" class="input" v-model.number="item[col.columns]"
              :type="['Integer','Money'].includes(col.col_type)?'digit': 'text'" :placeholder="'输入'+col.label"
              @input="changeValue(index,'list')" v-if="['Integer','Money'].includes(col.col_type)" />
            <uni-easyinput primaryColor="#38C09E" class="input" v-model="item[col.columns]" type="text"
              :placeholder="'输入'+col.label" @input="changeValue(index,'list')" v-else />
          </view>
          <text v-else> {{setCellVal(item[col.columns])||''|hideYear(removeYearFromDate)}}</text>
        </view>
        <button class="cuIcon-right cu-btn bg-white  more-btn " v-if="showHandle&&showButton(item)"
          @click.stop="showAction(item)"></button>
        <view class="flex align-center border-right" v-else-if="showDelete&&!disabled" @click.stop>
          <text class="cuIcon-delete text-black" @click.stop="onChildFormBtn({button_type:'delete'},index)"></text>
        </view>
      </view>
      <view class="list-item" v-for="(item,index) in initData" @click="onButton({button_type:'editInit'},index)">
        <view class="col-item selection" @click.stop="changeChecked(index,'initData')" v-if="showSelection">

          <text class="cuIcon-squarecheckfill text-green" v-if="initChecked&&initChecked.includes(index)"></text>

          <text class="cuIcon-square" v-else></text>

        </view>
        <view class="col-item" v-for="col in showColumn" :key="col.columns"
          :style="{'min-width':colMinWidth&&colMinWidth[col.columns]?colMinWidth[col.columns]:''}">
          <view v-if="inlineEditCols(col.columns,item)" @click.stop="" class="input-box">
            <uni-easyinput primaryColor="#38C09E" class="input" v-model.number="item[col.columns]"
              :type="['Integer','Money'].includes(col.col_type)?'digit': 'text'" :placeholder="'输入'+col.label"
              @input="changeValue(index,'init')" v-if="['Integer','Money'].includes(col.col_type)" />
            <uni-easyinput primaryColor="#38C09E" class="input" v-model="item[col.columns]" type="text"
              :placeholder="'输入'+col.label" @input="changeValue(index,'init')" v-else />
          </view>
          <text v-else> {{setCellVal(item[col.columns])||''|hideYear(removeYearFromDate)}}</text>
        </view>
        <view class="flex align-center border-right" v-if="showDelete" @click.stop>
          <text class="cuIcon-delete text-black"
            @click.stop="onChildFormBtn({button_type:'delete_init'},index,true)"></text>
        </view>
      </view>
      <view class="list-item" v-for="(item,index) in memoryListData" @click="onButton({button_type:'editMem'},index)">
        <view class="col-item selection" @click.stop="changeChecked(index,'memoryListData')" v-if="showSelection">

          <text class="cuIcon-squarecheckfill text-green" v-if="memChecked&&memChecked.includes(index)"></text>

          <text class="cuIcon-square" v-else></text>

        </view>
        <view class="col-item" v-for="col in showColumn" :key="col.columns"
          :style="{'min-width':colMinWidth&&colMinWidth[col.columns]?colMinWidth[col.columns]:''}">
          <view v-if="inlineEditCols(col.columns,item)" @click.stop="" class="input-box">
            <uni-easyinput primaryColor="#38C09E" class="input" v-model.number="item[col.columns]"
              :type="['Integer','Money'].includes(col.col_type)?'digit': 'text'" :placeholder="'输入'+col.label"
              @input="changeValue(index,'mem')" v-if="['Integer','Money'].includes(col.col_type)" />
            <uni-easyinput primaryColor="#38C09E" class="input" v-model="item[col.columns]" type="text"
              :placeholder="'输入'+col.label" @input="changeValue(index,'mem')" v-else />
          </view>
          <text v-else> {{setCellVal(item[col.columns])||''|hideYear(removeYearFromDate)}}</text>
        </view>
        <view class="flex align-center border-right" v-if="showDelete" @click.stop>
          <text class="cuIcon-delete text-black" @click.stop="onChildFormBtn({button_type:'delete'},index,true)"></text>
        </view>
      </view>
      <view class="list-item" v-if="finalListData.length===0&&total===0">
        <view class="col-item">
          暂无数据
        </view>
      </view>
    </view>
    <view class="unfold" v-if="config.isFold!==true&&config.unfold ===true" @click="unfold">
      <!-- <text>向上折叠</text> -->
      <text class="cuIcon-fold"></text>
    </view>
    <view class="cu-modal" @click.stop="hideModal" :class="{show:modalName==='addChildData'}">
      <view class="cu-dialog" @click.stop.prevent="" v-if="addV2&&modalName==='addChildData'">

        <view class="close-btn text-right">
          <text></text>
          <view class="title">
            {{add_service_view_name||''}}
          </view>
          <!-- <text class="title"></text> -->
          <button class="cu-btn  shadow-blur" @click.stop="hideModal()"><text class="cuIcon-close"></text></button>
        </view>
        <view class="" style="padding: 2rem;max-height: 80vh;max-width: 70vw;overflow-y: scroll;">
          <view class="child-form-wrap">
            <view class="custom-form" v-if="addService==='srvmkt_promotion_goods_add'">
              <view class="form-item">
                <view class="label">
                  <text class="text-red">*</text>活动商品
                </view>
                <view class="value border">
                  <select-lazy name="goods_name" slabel="goods_name" svalue="goods_no" :value="goods_no"
                    :options="allGoodsList" @selectitem="selectitem" @on-change="onSearch">
                  </select-lazy>
                  <!-- <uni-easyinput primaryColor="#38C09E" placeholder="选择套餐商品" /> -->
                </view>
              </view>
            </view>
            <view class="custom-form" v-else-if="addService==='srvretail_package_detail_add'">
              <view class="form-item">
                <view class="label">
                  <text class="text-red">*</text>套餐商品
                </view>
                <view class="value border">
                  <select-lazy name="goods_name" slabel="goods_name" svalue="goods_no" :value="goods_no"
                    :options="allGoodsList" @selectitem="selectitem" @on-change="onSearch">
                  </select-lazy>
                  <!-- <uni-easyinput primaryColor="#38C09E" placeholder="选择套餐商品" /> -->
                </view>
              </view>
              <view class="form-item">
                <view class="label">
                  <text class="text-red">*</text>数量
                </view>
                <view class="value">
                  <uni-easyinput v-model.number="goods_num" type="digit" primaryColor="#38C09E" placeholder="请输入数量" />
                </view>
              </view>
            </view>

            <b-form class="bx-form-wrap" :srvApp="srvApp" v-else-if="allFields && isArray(allFields)"
              :fields="allFields" :pageType="use_type" :formType="'add'" ref="childForm" :key="modalName"
              @value-blur="valueChange" :main-data="mainData"></b-form>
          </view>
          <view class="button-box justify-center text-center" v-if="addV2&&addV2.formButton">
            <button class="button  flex-1" v-for="(btn,index) in addV2.formButton" :key="index"
              @click="onChildFormBtn(btn)">{{btn.button_name||''}}</button>
          </view>
        </view>
      </view>
    </view>

    <view class="cu-modal" @click.stop="hideModal" :class="{show:modalName==='updateChildData'}">
      <view class="cu-dialog" @click.stop.prevent="" v-if="updateV2&&modalName==='updateChildData'">
        <view class="close-btn text-right">
          <text></text>
          <view class="title">
            {{update_service_view_name||''}}
          </view>
          <button class="cu-btn  shadow-blur" @click.stop="hideModal()"><text class="cuIcon-close"></text></button>
        </view>
        <view class="" style="padding: 2rem;max-height: 80vh;max-width:800px;overflow-y: scroll;">
          <view class="child-form-wrap">
            <view class="custom-form" v-if="updateService==='srvretail_package_detail_update'">
              <view class="form-item">
                <view class="label">
                  <text class="text-red">*</text>套餐商品
                </view>
                <view class="value">
                  <select-lazy name="goods_name" slabel="goods_name" svalue="goods_no" :value="goods_no"
                    :options="allGoodsList" @selectitem="selectitem" @on-change="onSearch">
                  </select-lazy>
                </view>
              </view>
              <view class="form-item">
                <view class="label">
                  <text class="text-red">*</text>数量
                </view>
                <view class="value">
                  <uni-easyinput v-model.number="goods_num" type="digit" primaryColor="#38C09E" placeholder="请输入数量" />
                </view>
              </view>
            </view>
            <b-form class="bx-form-wrap" v-else-if="allFields && isArray(allFields)" :fields="allFields"
              :main-data="mainData" :pageType="use_type" :formType="'update'" ref="childForm" :key="modalName"
              @value-blur="updateValueChange">
            </b-form>
          </view>
          <view class="button-box" v-if="updateV2&&modalName==='updateChildData'&&updateV2.formButton">
            <button class="button  flex-1" v-for="(btn,idx) in updateV2.formButton" :key="idx"
              @click="onChildFormBtn(btn)">{{btn.button_name||''}}</button>
          </view>
        </view>
      </view>
    </view>

    <batch-add ref="batchAdd" :main-data="mainData" :selectColInfo="selectColInfo" @submit="batchSubmit">
    </batch-add>
    <u-action-sheet :list="listItemAction" @click="clickActionItem" v-model="showActionSheet"></u-action-sheet>
  </view>
</template>

<script>
  import batchAdd from '@/pages/public/components/batch-add/batch-add.vue'
  import bForm from './a-form/a-form.vue'
  // import aForm from '@/components/a-form/a-form.vue'

  export default {
    components: {
      batchAdd,
      'b-form': bForm
      // aForm: () => import('@/components/a-form/a-form.vue'),
    },
    data() {
      return {
        goods_no: "",
        goods_num: '',
        goodsList: [],
        allGoodsList: [],
        templatePopup: false,
        templates: [],
        templateList: [],
        curTemplate: "",
        v2Data: null,
        addV2: null,
        updateV2: null,
        localListData: [],
        listData: [],
        total: '0',
        rownumber: 10,
        orderCols: [],
        loading: false,
        modalName: "",
        memoryListData: [],
        currentItemIndex: null,
        currentItemType: null,
        selectColInfo: null,
        initData: [],
        curItem: null,
        allFields: [],
        listItemAction: [],
        showActionSheet: false,
        fk_condition: null,
        use_type: 'detaillist',
        checkedList: [],
        listChecked: [],
        memChecked: [],
        initChecked: [],
        // isSelectAll:false
      }
    },
    filters: {
      hideYear: (value, isHide) => {
        if (value && isHide) {
          let year = (new Date()).getFullYear()
          value = value.replace(`${year}-`, '')
        }
        return value || ''
      }
    },
    props: {
      srvType: {
        type: String
      },
      mainTable: {
        type: String
      },
      mainServiceName: {
        type: String
      },
      appName: {
        type: String
      },
      config: {
        type: Object
      },
      mainData: {
        type: Object
      },
      mainFkField: {
        type: Array
      },
      disabled: {
        type: [String, Boolean]
      },
      srvGridButtonDisp: {
        type: Object
      },
      srvRowButtonDisp: {
        type: Object
      },
      srvMoreConfig: {
        type: Object
      },
      fkCondition: {
        type: [Array, Object]
      },
      fkInitVal: {
        type: [Array, Object]
      },
      childListData: {
        type: Object
      }
    },
    watch: {
      modalName: {
        immediate: true,
        handler(newValue) {
          let allFields = []
          if (newValue === 'addChildData') {
            this.use_type = 'add'
            if (Array.isArray(this.addV2?._fieldInfo)) {
              allFields = this.deepClone(this.addV2?._fieldInfo)
            }
          } else if (newValue === 'updateChildData') {
            this.use_type = 'update'
            if (Array.isArray(this.updateV2?._fieldInfo)) {
              allFields = this.deepClone(this.updateV2?._fieldInfo)
            }
          } else {
            this.use_type = this.config?.use_type || 'detaillist'
          }
          this.allFields = allFields.map(item => {
            if (this.fk_condition && this.fk_condition[item.column]) {
              item.fk_condition = this.fk_condition[item.column]
            }
            return item
          })
        },
      },
      finalListData: {
        deep: true,
        handler(newValue, oldValue) {
          this.$emit('child-list-change', {
            calcRelations: this.config?.calcRelations,
            key: this.config?.foreign_key?.constraint_name || this.config?.foreign_key?.key_no,
            data: newValue,
            list: this.getChildDataList()
          })
        }
      }
    },
    computed: {
      isHalfSelect() {
        if ((this.listChecked.length > 0 || this.memChecked.length > 0 ||
            this.initChecked.length > 0) && !this.isSelectAll) {
          return true
        } else {
          return false
        }
      },
      isSelectAll() {
        if (this.listChecked.length === this.listData.length && this.memChecked.length === this.memoryListData.length &&
          this.initChecked.length === this.initChecked.length && (this.listChecked.length !== 0 || this.memChecked
            .length !== 0 || this.initChecked.length !== 0)) {
          return true
        } else {
          return false
        }
      },
      update_service_view_name() {
        return this.updateV2?.update_service_view_name
      },
      add_service_view_name() {
        return this.addV2?.service_view_name
      },
      inlineEditCols() {
        return (col, rowData) => {
          let res = false
          rowData = rowData?._rowData || rowData || {}
          if (col && this.config.inlineEditCols && this.config.inlineEditCols.indexOf(col) !== -1) {
            res = true
            if (Array.isArray(this.config.inlineEditColsCondition) && this.config
              .inlineEditColsCondition
              .length > 0) {
              let num = 0;
              this.config.inlineEditColsCondition.forEach(cond => {
                if (cond.ruleType === 'like') {
                  if (rowData && rowData[cond.colName] && rowData[cond.colName].indexOf(cond
                      .value) !== -1) {
                    num++
                  }
                } else if (cond.ruleType === 'eq') {
                  if (rowData && rowData[cond.colName] && rowData[cond.colName] === cond
                    .value) {
                    num++
                  }
                } else if (cond.ruleType === 'ne') {
                  if (rowData && rowData[cond.colName] && rowData[cond.colName].indexOf(cond
                      .value) === -1) {
                    num++
                  }
                }
              })
              res = num === this.config.inlineEditColsCondition.length
            }
          }
          return res
        }
      },
      showSelection() {
        return this.v2Data?.moreConfig?.selection === true && this.srvType !== 'detail'&&this.addService!=='srvmkt_promotion_goods_add'
      },
      explainFields() {
        return this.config?.foreign_key?.moreConfig?.explainFields || {}
      },
      // fkTemplate() {
      //   return this.config?.constraint_name && this.srvMoreConfig?.fkTemplate[this.config?.constraint_name] || false
      // },
      templateButtonLabel() {
        return this.fkTemplate?.buttonLabel
      },
      handlerButton() {
        return this.srvMoreConfig
      },
      showHandle() {
        // 是否显示操作按钮
        let res = true
        if (Array.isArray(this.rowButton) && this.rowButton.length == 0) {
          res = false
        }
        if (this.disabled) {
          res = false
        }

        let constraint_name = this.config?.foreign_key?.constraint_name || this.config?.foreign_key?.key_no
        if (constraint_name && this.srvRowButtonDisp && this.srvRowButtonDisp[constraint_name] && this
          .srvRowButtonDisp[
            constraint_name]['handle'] === false) {
          res = false
        }
        if (this.use_type && this.use_type.indexOf('detail') == -1) {
          res = false
        }
        return res
      },
      theme() {
        return this.$store?.state?.app?.theme
      },
      curV2() {
        if (this.modalName === 'addChildData') {
          return this.addV2
        } else if (this.modalName === 'updateChildData') {
          return this.updateV2
        }
      },
      showSeeAll() {
        if (this.v2Data?.moreConfig?.gridButtonDisp?.seeAll === false) {
          return false
        }
        if (this.fkMoreConfig?.gridButtonDisp?.seeAll === false) {
          return false
        }
        let constraint_name = this.config?.foreign_key?.constraint_name || this.config?.foreign_key?.key_no
        if (this.srvGridButtonDisp && constraint_name && this.srvGridButtonDisp[constraint_name]) {
          if (this.srvGridButtonDisp[constraint_name]['seeAll'] === false) {
            return false
          }
        }
        if (this.total <= this.listData.length) {
          return false
        }
        return true
      },
      batchDelete() {
        return this.rowButton.find(item => item.button_type === 'delete')
      },
      rowButton() {
        let rowButton = this.v2Data?.rowButton
        if (Array.isArray(rowButton)) {
          return rowButton.filter(item => !['duplicatedeep', 'duplicate'].includes(item.button_type))
        } else {
          return []
        }
      },
      calcRelations() {
        return this.config?.calcRelations
      },
      fkMoreConfig() {
        return this.config?.foreign_key?.moreConfig
      },
      showDelete() {
        return this.use_type && ['update', 'add', 'addchildlist', 'updatechildlist'].includes(this.use_type) &&
          this
          .config?.showDelete !== false
      },
      setListData() {
        return this.listData.filter(item => item._dirtyFlags !== "delete")
      },
      finalListData() {
        return [...this.listData, ...this.memoryListData, ...this.initData].filter(item => item._dirtyFlags !==
          'delete')
      },
      // use_type() {
      //   return this.config?.use_type || this.v2Data?.use_type
      // },
      condition() {
        const foreignKey = this.foreignKey
        const data = this.config
        let formData = this.mainData;
        if (!foreignKey || !formData) {
          return []
        }
        let condition = [{
          colName: foreignKey.column_name,
          ruleType: 'eq',
          value: formData[foreignKey.referenced_column_name]
        }];
        if (data?.srv_app && data?.service_name && foreignKey) {
          condition = [{
            colName: foreignKey.ref_service_column,
            ruleType: "eq",
            value: formData[foreignKey.refed_service_column]
          }];
        }
        return condition
      },
      addService() {
        if (this.serviceName) {
          let index = this.serviceName.lastIndexOf('_')
          return this.serviceName.slice(0, index) + '_add'
        }
      },
      updateService() {
        if (Array.isArray(this.v2Data?.rowButton) && this.v2Data.rowButton.find(item => item.button_type ===
            'edit')) {
          let buttonInfo = this.v2Data.rowButton.find(item => item.button_type === 'edit')
          return buttonInfo?.service_name
        }
        if (this.serviceName) {
          let index = this.serviceName.lastIndexOf('_')
          return this.serviceName.slice(0, index) + '_update'
        }
      },
      deleteService() {
        if (this.serviceName) {
          let index = this.serviceName.lastIndexOf('_')
          return this.serviceName.slice(0, index) + '_delete'
        }
      },
      selectService() {
        if (this.serviceName) {
          let index = this.serviceName.lastIndexOf('_')
          return this.serviceName.slice(0, index) + '_select'
        }
      },
      serviceName() {
        return this.config?.service_name
      },
      foreignKey() {
        return this.config?.foreign_key
      },
      appTempColMap() {
        // 字段关系映射
        return this.moreConfig?.appTempColMap || {}
      },
      moreConfig() {
        return this.v2Data?.moreConfig
      },
      srvApp() {
        return this.config?.srv_app || this.config?.appName || this.appName || uni.getStorageSync('activeApp')
      },
      publicButton() {
        let result = []
        if (Array.isArray(this.v2Data?.gridButton)) {
          let ignoreBtn = ['select', 'batch_delete', 'delete', "batchupdate"]
          if (this.use_type === 'detaillist') {
            // ignoreBtn.push('add')
          }

          result = this.v2Data.gridButton.filter(item => {
            // 外键关系上配置的隐藏按钮
            if (item.permission === false) {
              return false
            }
            if (this.fkMoreConfig?.gridButtonDisp && this.fkMoreConfig?.gridButtonDisp[item
                .button_type] ===
              false) {
              return false
            }
            // 当前子表服务上配置的隐藏按钮
            if (this.v2Data?.moreConfig?.gridButtonDisp && this.v2Data?.moreConfig?.gridButtonDisp[item
                .button_type] ===
              false) {
              return false
            }
            // 主表服务上配置的隐藏按钮
            let constraint_name = this.config?.foreign_key?.constraint_name || this.config?.foreign_key
              ?.key_no
            if (constraint_name && this.srvGridButtonDisp && this.srvGridButtonDisp[constraint_name] &&
              this
              .srvGridButtonDisp[constraint_name][item.button_type] === false) {
              return false
            }
            return item.permission === true && !ignoreBtn.includes(item
              .button_type)
          })
          if (this.config?.foreign_key?.moreConfig?.childListConfig?.batch_add?.target_column) {

          }
          if (this.v2Data?.moreConfig?.childListConfig?.batchAdd?.childservice === 'srvretail_act_goods_info_select') {
            let batch_add = this.v2Data?.moreConfig?.childListConfig?.batchAdd
            result.unshift({
              "page_type": "修改子列表",
              "button_name": batch_add?.buttonName || "添加",
              "button_type": "add",
              "service_name": 'srvmkt_promotion_goods_add',
              "service_view_name": "活动商品增加",
              "always_show": false,
              "permission": true,
              "client_type": "PC,APP",
              "tip_msg": null,
              "biz_authority_cfg": null,
              "application": "retail",
              "is_public": true,
              "id": 58,
              "page_area": "表格按钮",
              "seq": 100,
            })
          }

          // if (this.batchDelete?.button_type) {
          //   result.push({
          //     ...this.batchDelete,
          //     _button_type: 'batchDelete'
          //   })
          // }

          if (this.v2Data?.moreConfig?.childListConfig?.batchAdd?.dependField && !result.find(item => item
              .button_type === 'add')) {
            let batch_add = this.v2Data?.moreConfig?.childListConfig?.batchAdd
            result.unshift({
              "page_type": "修改子列表",
              "button_name": batch_add?.buttonName || "添加",
              "button_type": "add",
              "service_name": "srvretail_package_detail_add",
              "service_view_name": "组合套餐明细增加",
              "always_show": false,
              "permission": true,
              "client_type": "PC,APP",
              "tip_msg": null,
              "biz_authority_cfg": null,
              "application": "retail",
              "is_public": true,
              "id": 58,
              "page_area": "表格按钮",
              "seq": 100,
            })


          }
        }

        return result
      },
      colMinWidth() {
        return this.moreConfig?.tableConfig?.col_min_width
      },
      removeYearFromDate() {
        return this.moreConfig?.removeYearFromDate
      },
      showColumn() {
        let columns = []
        if (Array.isArray(this.moreConfig?.tableConfig?.columns) && this.moreConfig.tableConfig.columns.length >
          0) {
          return this.orderCols.filter(item => this.moreConfig.tableConfig.columns.includes(item.columns))
        } else if (this.moreConfig?.tableConfig?.columns && !Array.isArray(this.moreConfig?.tableConfig
            ?.columns)) {
          try {
            columns = this.moreConfig.tableConfig.columns.split(',')
            columns = this.orderCols.filter(item => columns.includes(item.columns))
          } catch (e) {
            //TODO handle the exception
            console.info(e)
          }
          if (columns.length > 0) {
            return columns
          }
        }

        if (Array.isArray(this.moreConfig?.childTableColumn) && this.moreConfig.childTableColumn.length > 0) {
          columns = this.orderCols.filter(item => this.moreConfig.childTableColumn.includes(item.columns))
        }
        if (Array.isArray(this.orderCols) && this.orderCols.length > 0) {
          columns = this.orderCols.filter(item => item.columns && item.columns !== 'id' && item.columns
            .indexOf('_no') == -1).slice(0, 10)
        }
        if (Array.isArray(columns) && columns.length > 0) {
          columns = columns.map(item => {
            if (item.more_config && typeof item.more_config === 'string') {
              try {
                item.moreConfig = JSON.parse(item.more_config)
              } catch (e) {
                //TODO handle the exception
              }
            }
            return item
          })
        }
        return columns
      },
      labelMap() {
        // 字段对应的label
        if (Array.isArray(this.orderCols) && this.orderCols.length > 0) {
          return this.orderCols.reduce((res, cur) => {
            res[cur.columns] = cur.label
            return res
          }, {})
        } else {
          return {}
        }
      },
    },
    created() {
      this.getListV2()

      if (this.config?.initDataCfg?.service && this.config?.initDataCfg?.rowData && this.srvType === 'add') {
        this.getInitData()
      } else if (Array.isArray(this.config?.defaultData) && this.config?.defaultData.length > 0) {
        this.initData = this.config?.defaultData.map(item => {
          return {
            ...item,
            _dirtyFlags: 'add',
            _isMemoryData: true
          }
        })
      }
    },
    beforeDestroy() {
      uni.$off('dataChange')
    },
    mounted() {
      let self = this
      uni.$on('dataChange', srv => {
        self.getList()
        this.memoryListData = []
      })
    },
    methods: {
      setCellVal(val){
        if(val===0){
          return '0'
        }else if(!val){
          return ''
        }else{
          return val
        }
      },
      async getInitData() {
        const config = this.config?.initDataCfg
        const app = config?.app || uni.getStorageSync('activeApp')
        const service = config?.service
        const url = `/${app}/select/${service}`
        const req = {
          "serviceName": service,
          "queryMethod": "select",
          "colNames": ["*"],
          "condition": config?.condition || [],
          "page": {
            "pageNo": 1,
            "rownumber": 20
          },
        }
        const res = await this.$http.post(url, req)

        if (res?.data?.state == 'SUCCESS' && Array.isArray(res.data.data) && res.data.data.length > 0) {
          let rowData = config?.rowData;
          this.initData = res.data.data.map(item => {
            let obj = {
              _dirtyFlags: 'add',
              _isMemoryData: true,
              _rowData: item,
            }
            Object.keys(rowData).forEach(key => {
              obj[key] = this.renderStr(rowData[key], {
                data: item
              })
            })
            return obj
          })
        }
      },
      onSearch(e) {
        const cond = [{
          colName: 'goods_name',
          ruleType: 'like',
          value: e
        }]
        this.getGoodsList(cond)
      },
      getGoodsList(cond) {
        const url = `/retail/select/srvretail_goods_info_check_select`
        const req = {
          "serviceName": "srvretail_goods_info_check_select",
          "colNames": ["*"],
          "condition": [{
            "colName": "store_no",
            "ruleType": "like",
            "value": ""
          }, {
            "colName": "goods_type",
            "ruleType": "eq",
            "value": "普通",
            "literalValue": true
          }],
          "page": {
            "pageNo": 1,
            "rownumber": 1000
          }
        }
        if (Array.isArray(cond)) {
          req.condition = cond
        }
        this.$http.post(url, req).then(res => {
          if (res.data.state === 'SUCCESS') {
            // this.goodsList = res.data.data
            let goodsList = [...this.allGoodsList, ...res.data.data]
            this.allGoodsList = goodsList.reduce((pre, cur) => {
              if (!pre.find(item => cur.goods_no === item.goods_no)) {
                pre.push(cur)
              }
              return pre
            }, [])
          }
        })
      },
      selectitem(index, item) {
        console.log(index, item);
        if (index >= 0) {
          this.goods_no = item.goods_no;
        } else {
          this.goods_no = ""
        }
      },
      bindPickerChange(e) {
        this.curTemplate = e.detail.value
        let cfg = this.fkTemplate
        this.getInitChildList(this.templateList[this.curTemplate]).then(data => {
          console.log(data);
          const globalVariable = {
            ...this.globalVariable,
            data: this.mainData,
            mainData: this.mainData,
            selectData: this.templateList[this.curTemplate]
          }
          if (Array.isArray(data) && data.length > 0) {
            data = data.map(item => {
              if (Object.keys(cfg?.defaultValue).length > 0) {
                Object.keys(cfg?.defaultValue).forEach(key => {
                  item[key] = this.renderStr(cfg?.defaultValue[key],
                    globalVariable)
                })
              }
              if (cfg?.excludeCols && Array.isArray(cfg?.excludeCols) && cfg?.excludeCols
                .length > 0) {
                cfg?.excludeCols.forEach(key => {
                  delete item[key]
                })
              }
              item["_isMemoryData"] = true
              item["_dirtyFlags"] = "add"
              return item
            })
          } else {
            data = []
          }
          if (Array.isArray(data)) {
            this.setInitData(data)
          }
        })

      },
      async getInitChildList(e) {
        let cfg = this.fkTemplate?.dataServiceCfg
        if (cfg) {
          let {
            app,
            service,
            condition
          } = cfg;

          app = app || this.fkTemplate?.app || uni.getStorageSync('activeApp')
          if (app && service) {
            if (Array.isArray(condition) && condition.length > 0) {
              condition = this.deepClone(condition)
              const globalVariable = {
                ...this.globalVariable,
                data: this.mainData,
                mainData: this.mainData,
                selectData: e
              }
              condition = condition.map(item => {
                item.value = this.renderStr(item.value, globalVariable)
                return item
              })
            }
            const url = `/${app}/select/${service}`
            const req = {
              "serviceName": service,
              "colNames": ["*"],
              "condition": condition || [],
              "page": {
                "pageNo": 1,
                "rownumber": 50
              }
            }
            const res = await this.$http.post(url, req);
            if (res?.data?.state === 'SUCCESS') {
              return res.data.data
            }
          }

        }
      },
      async getTemplate() {
        const {
          app,
          service,
          condition
        } = this.fkTemplate || {}
        if (app && service) {
          const url = `/${app}/select/${service}`
          const globalVariable = {
            ...this.globalVariable,
            mainData: this.mainData,
            config: this.config
          }
          let conditions = []
          if (Array.isArray(condition) && condition.length > 0) {
            conditions = this.deepClone(condition);
            conditions = conditions.map(item => {
              item.value = this.renderStr(item.value, globalVariable)
              return item
            })
          }
          const req = {
            "serviceName": service,
            "colNames": ["*"],
            "condition": conditions || [],
            "page": {
              "pageNo": 1,
              "rownumber": 100
            }
          }
          this.templates = []
          const res = await this.$http.post(url, req)
          if (res?.data?.state === 'SUCCESS') {
            this.templateList = res.data.data.map(item => {
              if (this.fkTemplate?.dispCol) {
                item._label = item[this.fkTemplate?.dispCol]
              }
              if (this.fkTemplate?.refedCol) {
                item._value = item[this.fkTemplate?.refedCol]
              }
              this.templates.push(item._label || item.value || '---')
              return item
            })
          }
        }
      },
      async changeTemplatePopup() {
        if (!this.templatePopup) {
          await this.getTemplate();
        }
        this.templatePopup = !this.templatePopup
      },
      hasHandlerButton(e) {
        let rowButton = []
        if (Array.isArray(this.rowButton) && this.rowButton.length > 0) {
          rowButton = this.deepClone(this.rowButton)
        }
        if (Array.isArray(e?._buttons) && e._buttons.length >= rowButton.length) {
          rowButton = rowButton.filter((item, index) => e._buttons[index] == 1 && !['duplicate'].includes(item
            .button_type))
        }
        return rowButton.length !== 0
      },
      closeAction() {
        this.listItemAction = []
      },
      clickActionItem(index) {
        let btn = this.listItemAction[index]
        let obj = {
          row: btn.rowData,
          button: btn
        }
        this.onFootButton(obj)
        this.showActionSheet = false
      },
      showButton(e) {
        let res = true
        if (this.disabled) {
          res = false
        }
        let rowButton = []
        if (Array.isArray(this.rowButton) && this.rowButton.length > 0) {
          rowButton = this.deepClone(this.rowButton).map(item => {
            item.text = item.button_name
            item.rowData = e
            return item
          })
        }
        if (Array.isArray(e?._buttons) && e._buttons.length >= rowButton.length) {
          rowButton = rowButton.filter((item, index) => e?._buttons[index] == 1 && !['duplicate',
              'duplicatedeep'
            ]
            .includes(item.button_type))
        }

        if (this.fkMoreConfig?.rowButtonDisp) {
          rowButton = rowButton.filter(item => {
            if (item.button_type === 'customize') {
              if (this.fkMoreConfig?.rowButtonDisp && this.fkMoreConfig?.rowButtonDisp[
                  'customize_hide']) {
                let customize_hide = this.fkMoreConfig?.rowButtonDisp['customize_hide']
                if (Array.isArray(customize_hide)) {
                  if (customize_hide.includes(item.id) || customize_hide.includes(item
                      .button_name)) {
                    res = false
                  }
                }
              }
            }
            if (this.fkMoreConfig?.rowButtonDisp[item.button_type] === false) {
              res = false
            } else if (this.fkMoreConfig?.rowButtonDisp[item.button_type] && typeof this.fkMoreConfig
              ?.rowButtonDisp[item.button_type] === 'string') {
              item.button_custom_name = this.fkMoreConfig?.rowButtonDisp[item.button_type]
            }
            res = true
          })
        }
        if (rowButton.length === 0) {
          res = false
        }
        if (rowButton.length === 1 && rowButton.find(item => item.button_type === 'detail')) {
          res = false
        }
        console.log(res);
        return res
      },
      showAction(e) {
        this.curItem = e;
        let rowButton = []
        if (Array.isArray(this.rowButton) && this.rowButton.length > 0) {
          rowButton = this.deepClone(this.rowButton).map(item => {
            item.text = item.button_name
            item.rowData = e
            return item
          })
        }
        if (Array.isArray(e?._buttons) && e._buttons.length >= rowButton.length) {
          rowButton = rowButton.filter((item, index) => e._buttons[index] == 1 && !['duplicate', 'duplicatedeep']
            .includes(item
              .button_type))
        }

        if (this.fkMoreConfig?.rowButtonDisp) {
          rowButton = rowButton.filter(item => {
            if (item.button_type === 'customize') {
              if (this.fkMoreConfig?.rowButtonDisp && this.fkMoreConfig?.rowButtonDisp[
                  'customize_hide']) {
                let customize_hide = this.fkMoreConfig?.rowButtonDisp['customize_hide']
                if (Array.isArray(customize_hide)) {
                  if (customize_hide.includes(item.id) || customize_hide.includes(item
                      .button_name)) {
                    return false
                  }
                }
              }
            }
            if (this.fkMoreConfig?.rowButtonDisp[item.button_type] === false) {
              return false
            } else if (this.fkMoreConfig?.rowButtonDisp[item.button_type] && typeof this.fkMoreConfig
              ?.rowButtonDisp[item.button_type] === 'string') {
              item.button_custom_name = this.fkMoreConfig?.rowButtonDisp[item.button_type]
            }
            return true
          })
        }
        let constraint_name = this.config?.foreign_key?.constraint_name || this.config?.foreign_key?.key_no
        if (constraint_name && this.srvRowButtonDisp && this.srvRowButtonDisp[constraint_name]) {
          rowButton = rowButton.filter((item, index) => {
            if (this.srvRowButtonDisp[constraint_name][item.button_type] === false) {
              return false
            }
            return true
          })
        }
        if (rowButton.length === 0) {
          uni.showToast({
            icon: 'none',
            title: "没有可用的操作"
          })
          return
        }
        // let sheets = rowButton.map(item => item.button_name)
        this.showActionSheet = true
        this.listItemAction = rowButton
      },
      async onFootButton(data) {
        let self = this
        let buttonInfo = this.deepClone(data.button);
        let rowData = this.deepClone(data.row);
        console.log(buttonInfo, rowData);
        if (buttonInfo?._buttons) {
          delete buttonInfo._buttons
        }
        if (!buttonInfo?.button_type) {
          uni.showModal({
            title: '提示',
            content: '按钮操作参数配置有误',
            showCancel: false
          })
          return
        }
        if (buttonInfo.operate_params && typeof buttonInfo.operate_params === 'string') {
          // 序列化操作参数
          try {
            buttonInfo.operate_params = JSON.parse(buttonInfo.operate_params);
            if (Array.isArray(buttonInfo.operate_params?.condition) && buttonInfo.operate_params.condition
              .length > 0) {
              buttonInfo.operate_params.condition.forEach(cond => {
                if (typeof cond.value === 'object' && cond.value.value_type === 'rowData') {
                  cond.value = rowData[cond.value.value_key];
                } else if (typeof cond.value === 'object' && cond.value.value_type ===
                  'constant') {
                  cond.value = cond.value.value;
                }
              });
              buttonInfo.operate_params.condition = buttonInfo.operate_params.condition.filter((
                item) => {
                if (item.value === null && item.ruleType == 'eq') {
                  return false
                }
                return true
              })
            }

            if (Array.isArray(buttonInfo.operate_params?.data) && buttonInfo.operate_params.data.length >
              0) {
              buttonInfo.operate_params.data.forEach(data => {
                if (typeof data === 'object') {
                  Object.keys(data).forEach(item => {
                    if (typeof data[item] === 'object' && data[item].value_type ===
                      'rowData') {
                      data[item] = rowData[data[item].value_key];
                    } else if (typeof data[item] === 'object' && data[item]
                      .value_type === 'constant') {
                      data[item] = data[item].value;
                    }
                  });
                }
              });
            }
          } catch (e) {
            //TODO handle the exception
          }
        }

        if (buttonInfo.button_type === "customize") {
          if (buttonInfo.operate_type === '删除') {
            this.onButtonToUrl(data, this.srvApp).then(res => {
              if (res.state === 'SUCCESS') {
                this.getList()
              }
            })

          } else if (buttonInfo.operate_type === '操作' && buttonInfo.operate_mode === '静默操作') {
            let req = [{
              serviceName: buttonInfo.operate_service,
              condition: buttonInfo.operate_params.condition,
              data: buttonInfo.operate_params.data
            }];
            if (!buttonInfo.operate_params.data && buttonInfo.servcie_type === 'update') {
              uni.showModal({
                title: '提示',
                content: '按钮操作参数配置有误',
                showCancel: false
              })
              return
            }
            let app = this.srvApp;
            let url = this.getServiceUrl(buttonInfo.application || app, buttonInfo.operate_service,
              buttonInfo.servcie_type);
            let res = await this.$http.post(url, req);
            if (res.data.state === 'SUCCESS') {
              // this.getList()
              this.getList()
            } else {
              uni.showModal({
                title: "提示",
                content: res.data.resultMessage,
                showCancel: false
              })
            }
            return
          } else if (buttonInfo.operate_type === '更新弹出' || buttonInfo.operate_type === '更新跳转') {
            // 自定义按钮
            let moreConfig = buttonInfo.more_config;
            if (moreConfig && typeof moreConfig === 'string') {
              try {
                moreConfig = JSON.parse(moreConfig);
              } catch (e) {
                //TODO handle the exception
                console.log(e);
              }
            }
            if (buttonInfo.servcie_type === 'add') {
              let params = {
                type: 'add',
                serviceName: buttonInfo.service_name,
                defaultVal: rowData,
                eventOrigin: buttonInfo
              };
              uni.navigateTo({
                url: '/pages/public/formPage/formPage?params=' + JSON.stringify(
                  params)
              });
              return
            } else if (buttonInfo.servcie_type === 'select') {
              let params = {
                type: 'select',
                serviceName: buttonInfo.service_name,
                defaultVal: rowData,
                eventOrigin: buttonInfo
              };
              if (buttonInfo.operate_params && Array.isArray(buttonInfo.operate_params
                  .condition)) {
                let viewTemp = {};
                if (buttonInfo.service_name ===
                  'srvhealth_store_vaccination_appoint_record_select') {
                  viewTemp = {
                    title: 'customer_name',
                    img: 'person_image',
                  }
                }
                uni.navigateTo({
                  url: '/publicPages/list/list?pageType=list&serviceName=' +
                    buttonInfo.service_name +
                    '&cond=' +
                    JSON.stringify(buttonInfo.operate_params.condition) +
                    '&viewTemp=' +
                    JSON.stringify(viewTemp)
                });
                return
              }
            } else if (buttonInfo.servcie_type === 'update' || buttonInfo.servcie_type === 'operate') {
              let params = {
                type: 'update',
                serviceName: buttonInfo.service_name,
                defaultVal: rowData,
                eventOrigin: buttonInfo
              };
              let fieldsCond = [];
              let condition = buttonInfo?.operate_params?.condition
              let defaultVal = buttonInfo?.operate_params?.data
              if (Array.isArray(defaultVal) && defaultVal.length > 0) {
                let obj = defaultVal[0]
                if (this.iObject(obj)) {
                  Object.keys(obj).forEach(key => {
                    fieldsCond.push({
                      column: key,
                      value: obj[key]
                    })
                  })
                }
              }

              if (fieldsCond.length === 0) {
                fieldsCond = [{
                  column: 'id',
                  value: rowData.id
                }]
              }
              let url =
                `/publicPages/formPage/formPage?service=${buttonInfo.service}&serviceName=${buttonInfo.service_name}&type=${buttonInfo.servcie_type}&fieldsCond=` +
                encodeURIComponent(JSON.stringify(fieldsCond));
              if (this.srvApp) {
                url += `&appName=${this.srvApp}`
              }
              if (Array.isArray(condition) && condition.length > 0) {
                url += `&condition=${JSON.stringify(condition)}`
              }
              uni.navigateTo({
                url: url
              });
              return
            }
            return
          } else if (buttonInfo.operate_type === '列表跳转') {

            let app = buttonInfo.application
            let url = '/publicPages/list2/list2?pageType=list&serviceName=' +
              buttonInfo.service_name +
              '&cond=' +
              JSON.stringify(buttonInfo.operate_params.condition)

            if (app) {
              url += `&destApp=${app}`
            }
            uni.navigateTo({
              url
            });
            return
          } else if (buttonInfo.operate_type === '增加跳转' || buttonInfo.operate_type === '增加弹出') {
            let fieldsCond = [];
            if (Array.isArray(buttonInfo.operate_params?.condition) && buttonInfo.operate_params.condition
              .length >
              0) {
              buttonInfo.operate_params.condition.forEach(item => {
                let obj = {
                  column: item.colName,
                  value: item.value,
                  disabled: true
                }
                fieldsCond.push(obj)
              })
            }
            if (Array.isArray(buttonInfo.operate_params?.data) && buttonInfo.operate_params.data.length >
              0) {
              buttonInfo.operate_params.data.forEach(item => {
                Object.keys(item).forEach(key => {
                  let obj = {
                    column: key,
                    value: item[key],
                    disabled: true
                  }
                  fieldsCond.push(obj)
                })

              })
            }
            let url =
              `/publicPages/formPage/formPage?type=add&serviceName=${buttonInfo.service_name}&fieldsCond=${JSON.stringify(fieldsCond)}&destApp=${buttonInfo.application}`;
            uni.navigateTo({
              url
            });
            return
          }

        } else if (this.listType === 'proc') {
          if (buttonInfo && buttonInfo.button_type === 'edit' && rowData.proc_instance_no) {
            uni.navigateTo({
              url: '/publicPages/procDetail/procDetail?proc_instance_no=' + rowData
                .proc_instance_no
            });
          }
        } else {
          if (buttonInfo.button_type === 'detail' && this.detailType === 'custom' && this.customDetailUrl) {
            let storeInfo = this.$store?.state?.app?.storeInfo
            let bindUserInfo = this.$store?.state?.user?.storeUserInfo
            let targetUrl = this.customDetailUrl
            let obj = {
              data: rowData,
              rowData,
              storeInfo,
              bindUserInfo
            };
            obj = this.deepClone(obj)
            targetUrl = this.renderStr(this.customDetailUrl, obj)
            uni.navigateTo({
              url: targetUrl
            })
            return
          }

          this.onButtonToUrl(data, this.srvApp).then(res => {
            if (buttonInfo && buttonInfo.button_type === 'delete') {
              if (res.state === 'SUCCESS') {
                // this.getList()
                this.getList()
              }
            }
            if (buttonInfo && buttonInfo.button_type === 'detail') {
              let {
                row,
                button
              } = res
              let fieldsCond = []
              if (row && row.id) {
                fieldsCond = [{
                  column: 'id',
                  value: row.id,
                  display: false
                }]
              } else {
                if (typeof row == 'object' && Object.keys(row).length > 0) {
                  Object.keys(row).forEach(key => {
                    if (key !== '_buttons' && row[key]) {
                      let obj = {
                        column: key,
                        value: row[key] || ''
                      }
                      fieldsCond.push(obj)
                    }
                  })
                }
              }
              let url =
                `/publicPages/formPage/formPage?type=detail&serviceName=${button.service_name}&fieldsCond=${JSON.stringify(fieldsCond)}`
              // if (this.list_config?.detailPage === 'childTableList' || this.moreConfig?.detailPage ===
              //   'childTableList') {
              url =
                `/publicPages/detail/detail?serviceName=${button.service_name}&fieldsCond=${JSON.stringify(fieldsCond)}`
              // }

              if (this.hideChildList) {
                url =
                  `/publicPages/formPage/formPage?type=detail&serviceName=${button.service_name}&fieldsCond=${JSON.stringify(fieldsCond)}`
              }

              if (this.srvApp) {
                url += `&appName=${this.srvApp}`
              }
              // if (button.service_name === 'srvdaq_cms_content_select') {
              //   if (rowData.content_no) {
              //     uni.navigateTo({
              //       url: `/publicPages/article/article?serviceName=srvdaq_cms_content_select&content_no=${rowData.content_no}`
              //     });
              //   }
              //   return
              // }
              uni.navigateTo({
                url: url
              })
            } else if (buttonInfo && buttonInfo.button_type === 'customize') {
              // 自定义按钮
              let moreConfig = buttonInfo.more_config;
              if (moreConfig && typeof moreConfig === 'string') {
                try {
                  moreConfig = JSON.parse(moreConfig);
                } catch (e) {
                  //TODO handle the exception
                  console.log(e);
                }
              }
              if (buttonInfo.servcie_type === 'add') {
                let params = {
                  type: 'add',
                  serviceName: buttonInfo.service_name,
                  defaultVal: rowData,
                  eventOrigin: buttonInfo
                };
                uni.navigateTo({
                  url: '/pages/public/formPage/formPage?params=' + JSON.stringify(
                    params)
                });
              } else if (buttonInfo.servcie_type === 'select') {
                let params = {
                  type: 'select',
                  serviceName: buttonInfo.service_name,
                  defaultVal: rowData,
                  eventOrigin: buttonInfo
                };
                if (buttonInfo.operate_params && Array.isArray(buttonInfo.operate_params
                    .condition)) {
                  let viewTemp = {};
                  if (buttonInfo.service_name ===
                    'srvhealth_store_vaccination_appoint_record_select') {
                    viewTemp = {
                      title: 'customer_name',
                      img: 'person_image',
                    }
                  }
                  uni.navigateTo({
                    url: '/publicPages/list/list?pageType=list&serviceName=' +
                      buttonInfo.service_name +
                      '&cond=' +
                      JSON.stringify(buttonInfo.operate_params.condition) +
                      '&viewTemp=' +
                      JSON.stringify(viewTemp)
                  });
                }
              } else if (buttonInfo.servcie_type === 'update') {
                let params = {
                  type: 'update',
                  serviceName: buttonInfo.service_name,
                  defaultVal: rowData,
                  eventOrigin: buttonInfo
                };
                let fieldsCond = [];
                if (Array.isArray(this.condition)) {
                  fieldsCond = this.condition.map(item => {
                    return {
                      column: item.colName,
                      value: item.value,
                      display: false
                    };
                  });
                }
                let condition = buttonInfo?.operate_params?.condition
                let defaultVal = buttonInfo?.operate_params?.data
                if (Array.isArray(defaultVal) && defaultVal.length > 0) {
                  let obj = defaultVal[0]
                  if (this.iObject(obj)) {
                    Object.keys(obj).forEach(key => {
                      fieldsCond.push({
                        column: key,
                        value: obj[key]
                      })
                    })
                  }
                }
                if (Array.isArray(condition) && condition.length > 0) {
                  condition.forEach(cond => {
                    fieldsCond.push({
                      column: cond.colName,
                      value: cond.value
                    })
                  })
                }
                let url =
                  `/publicPages/formPage/formPage?service=${buttonInfo.service}&serviceName=${buttonInfo.service_name}&type=${buttonInfo.servcie_type}&fieldsCond=` +
                  encodeURIComponent(JSON.stringify(fieldsCond));
                if (this.srvApp) {
                  url += `&appName=${this.srvApp}`
                }
                uni.navigateTo({
                  url: url
                });
              }
            } else if (buttonInfo && buttonInfo.button_type === 'duplicate') {
              let fieldsCond = []
              if (Array.isArray(self.condition)) {
                self.condition.forEach(item => {
                  fieldsCond.push({
                    column: item.colName,
                    value: item.value,
                    display: false
                  })
                })
              }
              Object.keys(rowData).forEach(key => {
                if (!['id', 'modify_user_disp', 'modify_user', 'modify_time',
                    'create_user_disp', 'create_user', 'create_time', 'del_flag',
                    '_buttons'
                  ].includes(key) && rowData[key]) {
                  if (!fieldsCond.find(item => item.column === key)) {
                    fieldsCond.push({
                      column: key,
                      display: true,
                      value: rowData[key],
                    })
                  }
                }
              })

              let url =
                `/publicPages/formPage/formPage?serviceName=${buttonInfo.service_name}&type=add&fieldsCond=${JSON.stringify(fieldsCond)}`;
              if (self.srvApp) {
                url += `&appName=${self.srvApp}`
              }
              uni.navigateTo({
                url: url
              });
            } else if (buttonInfo.servcie_type === 'add') {
              let params = {
                type: 'add',
                serviceName: res.button.service_name,
                defaultVal: res.row,
                eventOrigin: res.button
              };
              uni.navigateTo({
                url: '/pages/public/formPage/formPage?params=' + JSON.stringify(
                  params)
              });
            } else if (buttonInfo && buttonInfo.operate_type === '流程申请') {
              uni.navigateTo({
                url: '/pages/public/proc/apply/apply?serviceName=' + buttonInfo
                  .operate_service
              });
            }
          });
        }
        console.log('clickFootBtn:', data);


      },
      setInitData(e) {
        this.initData = e
      },
      unfold() {
        this.$emit('unfold', this.config)
      },
      /**
       * 生成主子表同时提交的子表请求参数
       */
      getChildDataList() {
        const fk = this.foreignKey
        const depend_keys = [{
          type: "column",
          depend_key: fk.referenced_column_name,
          add_col: fk.column_name
        }]
        let result = [];
        const deleteParams = this.buildDeleteParams()
        // deleteParams && result.push(deleteParams)
        const addParams = this.buildAddParams()
        // addParams && result.push(addParams)
        const updateParams = this.buildUpdateParams()
        result = [...result, ...deleteParams, ...addParams, ...updateParams]
        result = result.map(item => {
          item.depend_keys = depend_keys
          return item
        })
        return result
      },
      buildAllData() {
        // 除了已删除的其它所有数据
        let fk = this.foreignKey
        let list = this.finalListData.filter(item => !['delete'].includes(item._dirtyFlags))
        if (list.length === 0) {
          return []
        }
        list = this.deepClone(list)
        let params = list.map((item, index) => {
          let row = this.localListData[index]
          if (row) {
            let keys = Object.keys(row);
            if (Array.isArray(keys) && keys.length > 0) {
              keys.forEach(key => {
                if (row[key] === item[key]) {
                  delete item[key]
                }
              })
            }
          }
          return {
            serviceName: this.updateService,
            data: [item],
          }
        })
        return params
        // return {
        //   constraint_name: this.foreignKey?.constraint_name,
        //   list
        // }
      },
      buildDeleteParams() {
        let fk = this.foreignKey
        let deleteList = this.listData.filter(item => item._dirtyFlags === 'delete')
        if (deleteList.length === 0) {
          return []
        }
        deleteList = this.deepClone(deleteList)
        let ids = deleteList.map(row => row.id).join(",");
        let params = {
          condition: [{
            colName: 'id',
            ruleType: 'in',
            value: ids
          }],
          serviceName: this.deleteService
        }
        return [params]
      },
      buildUpdateParams() {
        let fk = this.foreignKey
        let updateList = this.finalListData.filter(item => item._dirtyFlags === 'update' && item.id)
        if (updateList.length === 0) {
          return []
        }
        updateList = this.deepClone(updateList)
        let params = updateList.map((item, index) => {
          delete item._isMemoryData
          delete item._dirtyFlags
          delete item._buttons
          if (item._rowData) {
            delete item._rowData
          }
          let row = this.localListData[index]
          let id = item.id
          Object.keys(row).forEach(key => {
            if (row[key] === item[key]) {
              delete item[key]
            }
          })
          return {
            serviceName: this.updateService,
            data: [item],
            condition: [{
              colName: "id",
              ruleType: "eq",
              value: id,
            }]
          }
        })
        return params
      },
      buildAddParams() {
        let fk = this.foreignKey
        let addList = this.finalListData.filter(item => item._dirtyFlags === 'add')
        if (addList.length === 0) {
          return []
        }
        addList = this.deepClone(addList)
        let params = {
          data: addList.map(item => {
            delete item._isMemoryData
            delete item._dirtyFlags
            delete item._buttons
            delete item._type
            if (item._rowData) {
              delete item._rowData
            }
            return item
          }),
          serviceName: this.addService
        }
        return [params]
      },
      deleteInitListItem(index) {
        if (index || index === 0) {
          this.initData.splice(index, 1)
        }
      },
      deleteMemoryListItem(index) {
        if (index || index === 0) {
          this.memoryListData.splice(index, 1)
        }
      },
      getMemoryData() {
        return this.memoryListData.map(item => {
          delete item._isMemoryData
          delete item._dirtyFlags
          if (item._rowData) {
            delete item._rowData
          }
          return item
        })
      },
      async onChildFormBtn(e, index, isMem) {
        // await new Promise((resolve) => {
        //   setTimeout(() => {
        //     resolve(true)
        //   }, 100)
        // })
        if (e && e.button_type) {
          switch (e.button_type) {
            case 'submit':
              this.add2List(e)
              break;
            case 'edit':
              this.updateChildListItem(index)
              break;
            case 'delete':
              if (this.use_type === "detaillist" && this.modalName === "updateChildData") {
                let id = this.listData[this.currentItemIndex]['id']
                uni.showModal({
                  content: "是否确认删除操作？",
                  success: (res) => {
                    if (res.confirm) {
                      console.log('用户点击确定');
                      let req = [{
                        "serviceName": e.service_name,
                        "colNames": ["*"],
                        "condition": [{
                          colName: 'id',
                          ruleType: 'eq',
                          value: id
                        }]
                      }]
                      if (!id) {
                        return
                      }
                      let appName = this.srvApp || uni.getStorageSync('activeApp');
                      this.onRequest("delete", e.service_name,
                        req, appName).then((res) => {
                        this.hideModal()
                        this.getList()
                        if (res.data.state === "SUCCESS") {
                          uni.showToast({
                            title: '操作成功',

                          })
                        } else {
                          uni.showModal({
                            title: '提示',
                            content: res.data
                              .resultMessage,
                            showCancel: false,
                          })
                        }
                      })
                    } else if (res.cancel) {
                      resolve('用户点击取消')
                    }
                  }
                })
                return
              }
              if (typeof index === 'number' && index >= 0) {
                if (isMem) {
                  this.deleteMemoryListItem(index)
                } else {
                  this.listData[index]._dirtyFlags = 'delete'
                  this.$set(this.listData, index, this.listData[index])
                }
              }
              break;
            case 'delete_init':
              this.deleteInitListItem(index)
              break;
            case 'reset':
              this.$refs.childForm.onReset()
              break;
          }
        }
      },
      changeValue(index, type) {
        if (type === 'mem') {
          this.memoryListData[index]._dirtyFlags = 'add'
        } else if (type === 'init') {
          this.initData[index]._dirtyFlags = 'add'
        } else {
          this.listData[index]._dirtyFlags = 'update'
        }
      },
      buildGoodsData1() {
        let data = null
        if (this.goods_no) {
          const goods = this.allGoodsList.find(item => item.goods_no === this.goods_no)
          data = {
            "promotion_no": this.mainData.promotion_no,
            "goods_name": goods?.goods_name,
            "goods_no": goods?.goods_no,
            "promotion_mode": this.mainData.promotion_mode,
            "sale_price": goods?.sale_price,
            "goods_barcode": goods?.goods_barcode,
            "goods_unit": goods?.goods_unit_name || goods?.goods_unit,
          }
        } else {
          if (!this.goods_no) {
            uni.showToast({
              title: '请选择商品',
              icon: 'none'
            })
          }
          return
        }
        return data

      },
      buildGoodsData() {
        let data = null
        if (this.goods_no && this.goods_num) {
          const goods = this.allGoodsList.find(item => item.goods_no === this.goods_no)
          data = {
            "goods_no": null,
            "goods_barcode": goods?.goods_barcode,
            "goods_name": goods?.goods_name,
            "package_goods_no": goods?.goods_no,
            "goods_unit": goods?.goods_unit_name || goods?.goods_unit,
            "goods_image": goods?.goods_image,
            "goods_stock": goods?.goods_stock,
            "goods_num": this.goods_num,
            "purchase_price": goods?.purchase_price,
            "sale_price": goods?.sale_price,
          }
        } else {
          if (!this.goods_no) {
            uni.showToast({
              title: '请选择商品',
              icon: 'none'
            })
          } else if (!this.goods_num) {
            uni.showToast({
              title: '请输入商品数量',
              icon: 'none'
            })
          }
          return
        }
        return data
      },
      updateChildListItem() {
        let data = null;
        if (this.updateService === 'srvretail_package_detail_update') {
          data = this.buildGoodsData()

        } else {
          data = this.$refs.childForm.getFieldModel()
        }
        if (!data) {
          return
        }
        if (this.use_type === 'detaillist') {
          // 详情子表页面 直接发请求修改
          let id = this.listData[this.currentItemIndex]['id']
          if (id && this.updateService) {
            let req = [{
              "serviceName": this.updateService,
              "condition": [{
                "colName": 'id',
                "ruleType": "eq",
                "value": id
              }],
              "data": [data]
            }]
            let app = this.srvApp || uni.getStorageSync('activeApp');
            let url = this.getServiceUrl(app, this.updateService, 'update');
            this.$http.post(url, req).then(res => {
              this.hideModal()
              this.getList()
            })
          }
          return
        }

        if (this.currentItemType === 'mem') {
          Object.assign(this.memoryListData[this.currentItemIndex], data)
          this.memoryListData[this.currentItemIndex]._dirtyFlags = 'add'
        } else if (this.currentItemType === 'init') {
          Object.assign(this.initData[this.currentItemIndex], data)
          this.initData[this.currentItemIndex]._dirtyFlags = 'add'
        } else {
          Object.assign(this.listData[this.currentItemIndex], data)
          this.listData[this.currentItemIndex]._dirtyFlags = 'update'
        }

        this.hideModal()
      },
      batchSubmit(arr) {
        this.$refs.batchAdd.close()
        let dependCols = []
        let batch_add = this.v2Data?.moreConfig?.childListConfig?.batchAdd
        let target_column = batch_add?.dependField
        let target_column_info = null
        if (Array.isArray(this.addV2?._fieldInfo) && this.addV2._fieldInfo.length > 0 && target_column) {
          target_column_info = this.addV2._fieldInfo.find(item => item.columns === target_column)
          this.addV2._fieldInfo.forEach(item => {
            if (item?.redundant?.dependField === target_column) {
              dependCols.push({
                refedCol: item?.redundant?.refedCol,
                columns: item.columns
              })
              return true
            }
          })
        }
        if (Array.isArray(arr) && arr.length > 0) {
          arr.forEach(data => {
            let obj = {
              [target_column_info.columns]: data[target_column],
            }
            // let numCol = this.config?.foreign_key?.moreConfig?.batch_add?.numCol
            // if (numCol) {
            //   obj[numCol] = data[numCol]
            // }
            dependCols.forEach(col => {
              obj[col.columns] = data[col.refedCol]
            })
            obj._isMemoryData = true
            obj._dirtyFlags = 'add'
            this.memoryListData.push(obj)
          })
        }
      },
      async add2List(e) {
        let data = null;
        if (this.addService === 'srvretail_package_detail_add') {
          data = this.buildGoodsData()
        } else if (this.addService === 'srvmkt_promotion_goods_add') {
          data = this.buildGoodsData1()
        } else {
          data = this.$refs.childForm.getFieldModel()
        }
        console.log(this.goodsList, data, this.goods_no);
        if (!data) {
          return
        }
        if (typeof data === 'object' && Object.keys(data).length > 0) {
          for (let key in data) {
            if (Array.isArray(data[key])) {
              data[key] = data[key].toString();
            }
            if (!data[key] && data[key] !== 0) {
              delete data[key]
            }
          }
          if ((this.use_type === 'detaillist' || this.v2Data?.use_type == 'detaillist') && this.srvType !==
            'update') {
            // 详情页面 直接添加
            let reqData = [{
              serviceName: e.service_name,
              data: [data]
            }];
            let app = this.srvApp || uni.getStorageSync('activeApp');
            let type = "add"
            let url = this.getServiceUrl(app, e.service_name, type);
            let res = await this.$http.post(url, reqData);
            this.getList()
            if (res.data.state === 'SUCCESS') {
              uni.showModal({
                title: '提示',
                content: res.data.resultMessage,
                showCancel: false
              })
            } else {
              uni.showToast({
                title: res.data.resultMessage,
                mask: false,
                icon: "none"
              });
            }
          } else {
            // 添加到内存中，随主表一起添加
            if (Object.keys(data).length > 0) {
              data._isMemoryData = true
              data._dirtyFlags = 'add'
              this.memoryListData.push(data)
            }
          }

        }
        this.addV2._fieldInfo = this.addV2._fieldInfo.map(item => {
          item.value = null
          if (item.defaultValue && !item.value) {
            item.value = item.defaultValue
          }
          if (Array.isArray(item?.option_list_v2?.conditions) && item.option_list_v2
            .conditions
            .length > 0) {
            item.option_list_v2.conditions = this.evalConditions(item.option_list_v2
              .conditions, this.defaultVal)
          }
          if (item.in_add === 1) {
            item.display = true
          }
          if (item.columns === this.foreignKey?.column_name) {
            item.display = false
            if (this.foreignKey?.referenced_column_name && this.mainData[this.foreignKey
                ?.referenced_column_name]) {
              item.value = this.mainData[this.foreignKey?.referenced_column_name]
            }
          }
          return item
        })

        this.modalName = ''
      },

      async updateValueChange(e, triggerField) {
        const column = triggerField.column
        let fieldModel = e
        const cols = this.allFields.filter(item => item.x_if && item.in_update === 1).map(item => item.column)
        const table_name = this.updateV2.main_table

        let result = null
        if (Array.isArray(cols) && cols.length > 0) {
          result = await this.evalX_IF(table_name, cols, fieldModel, this.srvApp)
        }

        let calcResult = {}
        let allFields = this.updateV2?._fieldInfo || []
        let calcCols = this.allFields.filter(item => item.redundant?.func && Array.isArray(item
            .calc_trigger_col) &&
          item.calc_trigger_col.includes(column)).map(item => item.column)
        // let calcCols = allFields.filter(item => item.redundant?.func && item.display).map(item => item.column)
        // let willCalc = calcCols.every(col => fieldModel[col] !== undefined && fieldModel[col] !== null)
        if (Array.isArray(calcCols) && calcCols.length > 0) {
          // if(willCalc){
          // calcResult = await this.evalCalc(table_name, calcCols, fieldModel, this.srvApp)
          // }
        }

        for (let i = 0; i < this.allFields.length; i++) {
          const item = this.allFields[i]
          item.old_value = item.value
          if (e && typeof e === 'object' && e.hasOwnProperty(item.column)) {
            item.value = e[item.column];
          }

          if (item.x_if) {
            if (Array.isArray(item.xif_trigger_col) && item.xif_trigger_col.includes(column)) {
              if (item.table_name !== table_name) {
                result = await this.evalX_IF(item.table_name, [item.column], fieldModel, this.srvApp)
              }
              if (result?.response && result.response[item.column]) {
                item.display = true
              } else if (result === true) {
                item.display = true
              } else {
                item.display = false
              }
            }
          }
          if (calcResult?.response && (calcResult.response[item.column] || calcResult.response[item
              .column] == 0)) {
            if (item.redundant?.trigger === 'always' || !item.value) {
              item.value = calcResult?.response[item.column] || item.value
              fieldModel[item.column] = item.value
            }
          }
          this.$set(this.allFields, i, item)
        }

      },
      async valueChange(e, triggerField) {
        const column = triggerField.column
        let fieldModel = e
        let allFields = this.addV2?._fieldInfo || []
        const cols = allFields.filter(item => item.x_if && item.in_add === 1).map(item => item.column)
        const table_name = this.curV2.main_table

        let result = null
        // if (Array.isArray(cols) && cols.length > 0) {
        //   debugger
        //   // result = await this.evalX_IF(table_name, cols, fieldModel, this.srvApp)
        // }

        let calcResult = {}

        // let calcCols = allFields.filter(item => item.redundant?.func && item.display).map(item => item.column)
        let calcCols = this.allFields.filter(item => item.redundant?.func && Array.isArray(item
            .calc_trigger_col) &&
          item.calc_trigger_col.includes(column)).map(item => item.column)
        if (Array.isArray(calcCols) && calcCols.length > 0) {
          // calcResult = await this.evalCalc(table_name, calcCols, fieldModel, this.srvApp)
        }

        for (let i = 0; i < allFields.length; i++) {
          const item = allFields[i]

          item.old_value = item.value
          if (e && typeof e === 'object' && e.hasOwnProperty(item.column)) {
            item.old_value = item.value;
            item.value = e[item.column];
          }
          if (calcResult?.response && (calcResult.response[item.column] || calcResult.response[item
              .column] == 0)) {
            if (item.redundant?.trigger === 'always' || !item.value) {
              item.value = calcResult?.response[item.column] || item.value
              fieldModel[item.column] = item.value
            }
          }

          if (item.x_if) {
            const res = eval(`(${item.x_if})(fieldModel)`)
            item.display = res
            if (res === false) {
              item.value = item.defaultValue
              if (Array.isArray(item.options)) {
                item.options = item.options.map(e => {
                  e.checked = false;
                  return e
                })
              }
            }
            // if (Array.isArray(item.xif_trigger_col) && item.xif_trigger_col.includes(column)) {
            //   if (item.table_name !== table_name) {
            //     result = await this.evalX_IF(item.table_name, [item.column], fieldModel, this.srvApp)
            //   }
            //   if (result?.response && result.response[item.column]) {
            //     item.display = true
            //   } else if (result === true) {
            //     item.display = true
            //   } else {
            //     item.value = item.defaultValue
            //     item.display = false
            //   }
            // }
          }
          this.allFields = allFields
          this.$set(this.allFields, i, item)
        }

        return
      },
      getCheckedData() {
        const listData = this.listData.filter((item, index) => this.listChecked.includes(index))
        const memoryListData = this.memoryListData.filter((item, index) => this.memChecked.includes(index))
        const initData = this.initData.filter((item, index) => this.initChecked.includes(index))
        const list = [...listData, ...memoryListData, ...initData]
        return {
          listData,
          memoryListData,

        }
      },
      selectAll() {
        this.listChecked = this.listData.map((item, index) => index)
        this.memChecked = this.memoryListData.map((item, index) => index)
        this.initChecked = this.initData.map((item, index) => index)
      },
      cancelSelectAll() {
        this.listChecked = []
        this.memChecked = []
        this.initChecked = []
      },
      changeChecked(index, type) {
        let list = []
        if (type === 'listData') {
          list = this.listChecked
        } else if (type === 'memoryListData') {
          list = this.memChecked
        } else if (type === 'initData') {
          list = this.initChecked
        }
        if (list.includes(index)) {
          list = list.filter(item => item !== index)
        } else {
          list.push(index)
        }
        this.listChecked = []
        this.memChecked = []
        this.initChecked = []
        if (type === 'listData') {
          this.listChecked = list
        } else if (type === 'memoryListData') {
          this.memChecked = list
        } else if (type === 'initData') {
          this.initChecked = list
        }

      },
      onBatchDelete(btn) {
        if (Array.isArray(this.listChecked) && this.listChecked.length > 0) {
          this.listData = this.listData.map((item, index) => {
            if (this.listChecked.includes(index)) {
              item._dirtyFlags = 'delete'
              this.listChecked = this.listChecked.filter(e => e !== index)
            }
            return item
          })
        }
        if (Array.isArray(this.memChecked) && this.memChecked.length > 0) {
          this.memoryListData = this.memoryListData.filter((item, index) => {
            if (this.memChecked.includes(index)) {
              this.memChecked = this.memChecked.filter(e => e !== index)
              return false
            }
            return true
          })
        }
        // if(Array.isArray(this.initChecked)&&this.initChecked.length>0){
        //   this.initData = this.initData.map((item,index)=>{
        //     if(this.initChecked.includes(index)){
        //       item._dirtyFlags==='delete'
        //     }
        //     return item
        //   })
        // }
        // this._dirtyFlags === 'delete'
        // const url = `/${btn.application}/operate/${btn.service_name}`
        // const req = [{

        // }]
      },
      async onButton(e, index) {
        if (e?._button_type === 'batchDelete') {
          this.onBatchDelete(e)
          return
        }
        this.goods_no = ''
        this.goods_num = ''
        if (e?.button_type == 'list') {

        } else if (this.disabled) {
          return
        }
        if (e && e.button_type) {
          switch (e.button_type) {
            case 'refresh':
              this.getList()
              break;
            case 'list':
              let url =
                `/publicPages/list2/list2?pageType=list&main_data=${JSON.stringify(this.mainData)}&serviceName=${this.serviceName}&destApp=${this.srvApp}&cond=${JSON.stringify(this.condition)}`
              if (this.disabled) {
                url += `&disabled=true`
              }
              uni.navigateTo({
                url
              })
              break;
            case 'add':
              this.getAddV2(e).then(_ => {
                if (this.addService === 'srvretail_package_detail_add' || this.addService ===
                  'srvmkt_promotion_goods_add') {
                  this.getGoodsList()
                }
                // this.modalName = 'addChildData'
                this.showModal('addChildData')
              })
              break;
            case 'edit':
              if (index || index === 0) {
                let row = this.listData[index]
                let rowButton = this.v2Data?.rowButton
                let detailBtn = null
                if (Array.isArray(rowButton) && rowButton.length > 0) {
                  detailBtn = rowButton.find(item => item.button_type === 'detail')
                }
                if (!detailBtn) {
                  return
                }
                let toDetail = this.config?.foreign_key?.moreConfig?.clickTarget === 'detail'
                let customDetailUrl = null
                if (this.srvMoreConfig) {
                  let constraint_name = this.config?.foreign_key?.constraint_name || this.config
                    ?.foreign_key
                    ?.key_no
                  if (constraint_name && this.srvMoreConfig[constraint_name]) {
                    const moreConfig = this.srvMoreConfig[constraint_name];
                    if (moreConfig?.clickTarget === 'detail') {
                      toDetail = true
                    }
                    if (moreConfig?.customDetailUrl) {
                      toDetail = true
                      let obj = {
                        ...this.globalVariable,
                        data: row,
                        rowData: row,
                      };
                      obj = this.deepClone(obj)
                      customDetailUrl = this.renderStr(moreConfig.customDetailUrl, obj)
                    }
                  }
                }

                if (toDetail && detailBtn) {
                  let fieldsCond = []
                  if (row && row.id) {
                    fieldsCond = [{
                      column: 'id',
                      value: row.id,
                      display: false
                    }]
                  } else {
                    if (typeof row == 'object' && Object.keys(row).length > 0) {
                      Object.keys(row).forEach(key => {
                        if (key !== '_buttons') {
                          let obj = {
                            column: key,
                            value: row[key] || ''
                          }
                          fieldsCond.push(obj)
                        }
                      })
                    }
                  }

                  if (this.config?.foreign_key?.moreConfig?.detailService) {
                    detailBtn.service_name = this.config?.foreign_key?.moreConfig?.detailService
                  }

                  let url =
                    `/publicPages/detail/detail?serviceName=${detailBtn.service_name}&fieldsCond=${JSON.stringify(fieldsCond)}`

                  if (this.config?.foreign_key?.moreConfig?.detailType === 'form-detail') {
                    url =
                      `/publicPages/formPage/formPage?type=detail&serviceName=${detailBtn.service_name}&fieldsCond=${JSON.stringify(fieldsCond)}`
                  }


                  if (this.config?.foreign_key?.moreConfig?.detailDisabled == true) {
                    url += '&disabled=true'
                  }
                  if (this.srvApp) {
                    url += `&appName=${this.srvApp}`
                  }

                  if (customDetailUrl) {
                    url = customDetailUrl
                  }

                  uni.navigateTo({
                    url: url
                  })
                } else {

                  this.getUpdateV2(row).then(_ => {
                    this.currentItemIndex = index
                    this.initGoodsData(this.currentItemType, this.currentItemIndex)
                    // this.modalName = 'updateChildData'
                    this.showModal('updateChildData')
                  })
                }
              }
              break;
            case 'editInit':
              // 编辑初始值表数据
              if (index || index === 0) {
                let row = this.initData[index]
                this.getUpdateV2(row).then(_ => {
                  this.currentItemIndex = index
                  this.currentItemType = 'init'
                  // this.modalName = 'updateChildData'
                  this.initGoodsData(this.currentItemType, this.currentItemIndex)
                  this.showModal('updateChildData')
                })

              }
              break
            case 'editMem':
              // 编辑内存表数据
              if (index || index === 0) {
                let row = this.memoryListData[index]
                this.getUpdateV2(row).then(_ => {
                  this.currentItemIndex = index
                  this.currentItemType = 'mem'
                  this.initGoodsData(this.currentItemType, this.currentItemIndex)
                  this.showModal('updateChildData')
                  // this.modalName = 'updateChildData'
                })
              }
              break
            case 'batchAdd':
              let addV2 = await this.getAddV2().then(_ => {
                this.$refs.batchAdd.open(e)
              })
              break;
          }
        }
      },
      initGoodsData(type, index) {
        if (this.updateService === 'srvretail_package_detail_update') {
          let listData = []
          if (type === 'mem') {
            listData = this.memoryListData
          } else if (this.currentItemType === 'init') {
            listData = this.initData
          } else {
            listData = this.listData
          }
          this.goods_no = listData[index].package_goods_no
          this.goods_num = listData[index].goods_num
          let cond = [{
            colName: 'goods_no',
            ruleType: 'like',
            value: this.goods_no
          }]
          this.getGoodsList(cond)
        }
      },
      async getUpdateV2(row, config) {
        if (this.updateV2?._fieldInfo) {
          this.updateV2._fieldInfo = this.updateV2._fieldInfo.map(item => {
            if (row && row[item.columns]) {
              item.value = row[item.columns]
            }
            return item
          })
          this.updateV2.rowData = row
          return
        }
        // if (this.config?.use_type === 'addchildlist' || this.config?.use_type === 'updatechildlist') {
        let app = this.srvApp || uni.getStorageSync('activeApp');
        let colVs = await this.getServiceV2(this.updateService, 'update', 'update', app);
        this.updateV2 = colVs

        colVs._fieldInfo = colVs._fieldInfo.map(item => {
          if (item?.option_list_v2?.refed_col && this.mainData[item.option_list_v2.refed_col]) {
            item.value = this.mainData[item.option_list_v2.refed_col]
          }
          if (Array.isArray(item?.option_list_v2?.conditions) && item.option_list_v2
            .conditions
            .length > 0) {
            item.option_list_v2.conditions = this.evalConditions(item.option_list_v2
              .conditions, this.mainData)
          }
          if (item.defaultValue) {
            item.value = item.defaultValue
          }
          if (item.in_update === 1) {
            item.display = true
          }
          if (item.columns === this.foreignKey?.ref_service_column) {
            item.display = false
          }
          if (item.columns === this.foreignKey?.column_name) {
            item.display = false
            if (this.foreignKey?.referenced_column_name && this.mainData[this.foreignKey
                ?.referenced_column_name] && !item.value) {
              item.value = this.mainData[this.foreignKey?.referenced_column_name]
            }
          }
          if (row && row[item.columns]) {
            item.value = row[item.columns]
          }

          let fkInitVal = this.fkInitVal
          // if (fkInitVal[item.column]&&item.display!==false) {
          if (fkInitVal && fkInitVal[item.column](item.display !== false || item.in_update !== 0)) {
            if (!item.value) {
              let obj = {
                mainData: this.mainData
              }
              let val = this.renderStr(fkInitVal[item.column], obj)
              if (val) {
                item.value = val
              }
            }
          }

          return item
        })
        colVs.rowData = row
        if (Array.isArray(colVs.formButton) && colVs.formButton.length > 0) {
          if (this.use_type === "detaillist") {
            colVs.formButton = colVs.formButton.map(item => {
              if (item.button_type === 'reset') {
                let rowButton = this.v2Data?.rowButton
                if (rowButton.length > 0) {
                  let delBtn = rowButton.find(item => item.button_type === 'delete')
                  if (delBtn) {
                    item = delBtn
                  }
                }
              }
              return item
            })
          }
          // colVs.formButton = colVs.formButton
        }

        if (this.fkMoreConfig?.rowButtonDisp) {
          colVs.formButton = colVs.formButton.filter(item => {
            if (this.fkMoreConfig.rowButtonDisp[item.button_type] === false) {
              return false
            } else {
              return true
            }
          })
        }
        let defaultVal = colVs._fieldInfo.reduce((res, cur) => {
          if (cur.value) {
            res[cur.columns] = cur.value
          }
          return res
        }, {})
        const cols = colVs._fieldInfo.filter(item => item.x_if && item.in_update === 1).map(item => item
          .column)
        const table_name = colVs.main_table
        const result = await this.evalX_IF(table_name, cols, defaultVal, this.srvApp)

        for (let i = 0; i < colVs._fieldInfo.length; i++) {
          const item = colVs._fieldInfo[i]
          if (item.x_if) {
            const res = eval(`(${item.x_if})(defaultVal)`)
            item.display = res
            if (res === false) {
              item.value = item.defaultValue
              if (Array.isArray(item.options)) {
                debugger
                item.options = item.options.map(e => {
                  e.checked = false;
                  return e
                })
              }
            }
            // if (Array.isArray(item.xif_trigger_col)) {
            //   if (item.table_name !== table_name) {
            //     result = await this.evalX_IF(item.table_name, [item.column], defaultVal, this.srvApp)
            //   }
            //   if (result?.response && result.response[item.column]) {
            //     item.display = true
            //   } else if (result === true) {
            //     item.display = true
            //   } else {
            //     item.display = false
            //   }
            // }
          }
        }
        if (Array.isArray(colVs.formButton)) {
          colVs.formButton.sort((a, b) => {
            if (a.button_type === 'edit' && b.button_type == 'reset') {
              return 1
            } else if (a.button_type === 'reset' && b.button_type == 'edit') {
              return -1
            } else {
              return 0
            }
          })
        }
        // this.updateV2 = colVs
        // }
      },
      async getAddV2(btn) {
        let self = this
        let serviceName = btn?.service_name || this.serviceName
        // if (this.config?.use_type === 'addchildlist' || this.config?.use_type === 'updatechildlist') {
        let app = this.srvApp || uni.getStorageSync('activeApp');
        let colVs = null
        if (this.addV2) {
          colVs = this.addV2
        } else {
          colVs = await this.getServiceV2(serviceName, 'add', 'add', app);
        }
        if (!colVs) {
          return
        }
        this.addV2 = colVs
        if (colVs.formButton && this.fkMoreConfig?.rowButtonDisp) {
          colVs.formButton = colVs.formButton.filter(item => {
            if (this.fkMoreConfig.rowButtonDisp[item.button_type] === false) {
              return false
            } else {
              return true
            }
          })
        }
        if (Array.isArray(colVs.formButton)) {
          colVs.formButton.sort((a, b) => {
            if (a.button_type === 'submit' && b.button_type == 'reset') {
              return 1
            } else if (a.button_type === 'reset' && b.button_type == 'submit') {
              return -1
            } else {
              return 0
            }
          })
        }
        colVs._fieldInfo = colVs._fieldInfo.map(item => {
          if (item.column && this.mainData && this.mainData[item.column]) {
            item.value = this.mainData[item.column]
          }
          if (Array.isArray(item?.option_list_v2?.mconditions) && item.option_list_v2
            .mconditions.length > 0) {
            let mconditions = item.option_list_v2.mconditions
            mconditions = mconditions.map(
              item => {
                item.value = this.renderStr(item.value, this.mainData)
                return item
              })
            if (Array.isArray(item?.option_list_v2?.conditions) && item.option_list_v2.conditions
              .length > 0) {
              item.option_list_v2.conditions = [...item.option_list_v2.conditions, ...
                mconditions
              ]
            } else {
              item.option_list_v2.conditions = mconditions
            }
          }
          if (item?.option_list_v2?.refed_col && this.mainData[item.option_list_v2.refed_col]) {
            if (Array.isArray(self.initData) && self.initData.length > 0 && self.initData.find(e =>
                e[item
                  .option_list_v2.refed_col] === self.mainData[item.option_list_v2.refed_col]
              )) {

            } else {
              let col = item.option_list_v2.refed_col
              // item.value = this.mainData[item.option_list_v2.refed_col]
            }
          }
          if (Array.isArray(item?.option_list_v2?.conditions) && item.option_list_v2.conditions
            .length > 0) {
            item.option_list_v2.conditions = this.evalConditions(item.option_list_v2.conditions,
              this.mainData)
          }
          if (item.defaultValue) {
            item.value = item.defaultValue
          }
          if (item.in_add === 1) {
            item.display = true
          }
          if (item.columns === this.foreignKey?.column_name) {
            item.display = false;
            if (this.foreignKey?.referenced_column_name && this.mainData[this.foreignKey
                ?.referenced_column_name]) {
              item.value = this.mainData[this.foreignKey?.referenced_column_name]
            }
          }
          if (item.col_type == self.mainTable) {
            if (Array.isArray(self.initData) && self.initData.length > 0 && self.initData.find(e =>
                e[item
                  .columns] === self.mainData[item.columns])) {

            } else {
              if (self.mainData && self.mainData[item.columns]) {
                item.value = self.mainData[item.columns]
                item.disabled = true
              }
            }

          }

          let fkInitVal = this.fkInitVal
          if (fkInitVal && fkInitVal[item.column] && (item.display !== false || item.in_add !== 0)) {
            let obj = {
              mainData: this.mainData
            }
            let val = this.renderStr(fkInitVal[item.column], obj)
            if (val) {
              item.value = val
              let defaultVal = colVs._fieldInfo.reduce((res, cur) => {
                if (cur.value) {
                  res[cur.columns] = cur.value
                }
                return res
              }, {})
              this.addV2 = colVs
              if (item.old_value !== item.value) {
                // this.valueChange(defaultVal, item)
              }
            }
            // }
          }

          return item
        })
        let defaultVal = colVs._fieldInfo.reduce((res, cur) => {
          if (cur.value) {
            res[cur.columns] = cur.value
          }
          return res
        }, {})
        const cols = colVs._fieldInfo.filter(item => item.x_if).map(item => item.column)
        const table_name = colVs.main_table
        const result = await this.evalX_IF(table_name, cols, defaultVal, this.srvApp)

        for (let i = 0; i < colVs._fieldInfo.length; i++) {
          const item = colVs._fieldInfo[i]
          if (item.x_if) {
            if (Array.isArray(item.xif_trigger_col)) {
              if (item.table_name !== table_name) {
                result = await this.evalX_IF(item.table_name, [item.column], defaultVal, this.srvApp)
              }
              if (result?.response && result.response[item.column]) {
                item.display = true
              } else if (result === true) {
                item.display = true
              } else {
                item.display = false
              }
            }
          }
        }

        if (Array.isArray(colVs?._fieldInfo)) {
          let colInfo = null
          let e = this.config?.foreign_key?.moreConfig?.batch_add
          if (e) {
            colInfo = colVs._fieldInfo.find(col => col.columns === e.target_column)
            if (Array.isArray(colInfo?.option_list_v2?.conditions) && colInfo.option_list_v2.conditions
              .length > 0) {
              colInfo.option_list_v2.conditions = colInfo.option_list_v2.conditions.map(item => {
                if (item.value && item.value.indexOf('data.') !== -1) {
                  let colName = item.value.slice(item.value.indexOf('data.') + 5);
                  if (this.mainData && this.mainData[colName]) {
                    item.value = this.mainData[colName];
                  }
                } else if (item.value && item.value.indexOf('top.user.user_no') !== -1) {
                  item.value = uni.getStorageSync('login_user_info').user_no;
                } else if (item.value && item.value.indexOf("'") === 0 && item.value
                  .lastIndexOf(
                    "'") === item.value
                  .length - 1) {
                  item.value = item.value.replace(/\'/gi, '');
                }
                if (item.value_exp) {
                  delete item.value_exp;
                }
                return item
              })
            }

            this.selectColInfo = colInfo
          }
        }
        return colVs
        // }
      },
      async getListV2() {
        let app = this.srvApp || uni.getStorageSync('activeApp');
        let use_type = this.config?.use_type || 'detaillist'
        let colVs = await this.getServiceV2(this.serviceName, 'list', use_type, app);
        if (!colVs) {
          return
        }
        // this.getAddV2()
        colVs.srv_cols = colVs.srv_cols.filter(item => {
          if (item.in_list !== 0) {
            if (item.in_list === 1) {
              item.display = true
            }
            return true
          }
        })
        if (colVs.more_config) {
          try {
            colVs.moreConfig = JSON.parse(colVs.more_config)
            delete colVs.more_config
          } catch (e) {
            //TODO handle the exception
            console.info(e)
          }
        }
        if (Array.isArray(colVs.srv_cols)) {
          this.orderCols = colVs.srv_cols.filter(item => {
            if (item.in_list === 1) {
              item.orderType = 'asc'
              item.selected = false;
              return true
            }
          })
        }
        this.v2Data = colVs;
        this.getList()
      },
      async getList() {
        const serviceName = this.serviceName
        const app = this.srvApp
        const url = this.getServiceUrl(app, serviceName, 'select');
        const foreignKey = this.foreignKey
        const data = this.config
        let formData = this.mainData;
        const condition = this.condition
        if (Array.isArray(condition) && condition.length > 0) {
          let req = {
            serviceName: serviceName,
            colNames: ['*'],
            condition: condition,
            page: {
              rownumber: this.rownumber,
              pageNo: 1
            }
          };
          if (this.loading) {
            return
          }
          if (this.v2Data?.vpage_no) {
            req.vpage_no = this.v2Data.vpage_no
          }
          this.loading = true
          if (this.config?.foreign_key?.moreConfig?.condition && Array.isArray(this.config?.foreign_key
              ?.moreConfig
              ?.condition)) {
            req.condition = [...req.condition, ...this.config.foreign_key.moreConfig.condition]
          }
          const res = await this.$http.post(url, req)
          this.loading = false
          if (res.data?.state === 'SUCCESS') {
            this.listData = res.data.data
            this.localListData = this.deepClone(res.data.data)
            this.total = res.data.page.total
            if (this.srvType === 'update' && res.data.data.length === 0 && this.config?.initDataCfg
              ?.service && this
              .config?.initDataCfg?.rowData) {
              this.getInitData()
            }
          }

        }
      },
      showModal(e) {
        if (Array.isArray(this.fkCondition) && this.childListData && typeof this.childListData === 'object') {
          let childData = this.deepClone(this.childListData)
          let fk_condition = {}
          this.fkCondition.forEach(item => {
            if (childData && item.from_constraint_name && childData[item.from_constraint_name]) {
              let target_col = item.target_col
              let from_col = item.from_col
              if (Array.isArray(childData[item.from_constraint_name])) {
                let val = childData[item.from_constraint_name].map(item => item[from_col])
                  .toString()
                if (val && item.colName && target_col) {
                  fk_condition[target_col] = [{
                    colName: item.colName,
                    ruleType: item.ruleType,
                    value: val
                  }]
                }
              }
            }
          })
          this.fk_condition = fk_condition
        }
        this.modalName = e
      },
      hideModal() {
        this.currentItemIndex = null
        this.currentItemType = null
        this.modalName = ''
      },
    }
  }
</script>

<style scoped lang="scss">
  .child-list {
    color: #666;
    background-color: #fff;
    padding: 1.5rem;
    padding-top: 0;
    font-size: 2.4rem;
    // border-radius: 1rem;
    width: 100%;

    .unfold {
      text-align: right;
      margin-top: 1rem;
      color: #000;
      flex: 1;
    }

    .section-name {
      color: #000;
      font-weight: bold;
      // padding-bottom: 1rem;
      border-bottom: 1rpx solid #F0F0F0;
      display: flex;
      justify-content: space-between;
      align-items: center;
      min-height: 6rem;

      .name {
        display: flex;
        flex: 1;
        justify-content: space-between;
        align-items: center;
      }

      .cu-load {
        line-height: 1;
        color: #666;
        font-weight: normal;
      }
    }

    .list-box {

      // margin-bottom: 1.5rem;
      .list-item {
        display: flex;
        border-bottom: 1px solid #f1f1f1;
        line-height: 30px;

        .bg-orange {
          background-color: #F3A250;

          &.light {
            background-color: #fde6d2;
          }
        }

        .more-btn {
          width: 30px;
          text-align: center;
          justify-content: center;
        }

        .hidden {
          opacity: 0;
          font-size: 2.4rem;
        }

        .cuIcon-add {
          border-radius: 10rpx;
          padding: 0 10rpx;
          display: flex;
          align-items: center;
        }

        &.table-head {
          font-size: 2.4rem;
          color: #666;
          background-color: #e5e5e5;
          line-height: 6rem;
        }

        .cuIcon-delete {
          line-height: 6rem;
          width: 6rem;
          text-align: center;

          &:active {
            color: red;
          }
        }

        .border-right {
          border-right: #e5e5e5 1px solid;
        }

        .col-item {
          flex: 1;
          text-align: center;

          min-height: 6rem;
          padding: .5rem;
          display: flex;
          align-items: center;
          justify-content: center;
          // max-width: 11vw;
          // overflow: hidden;
          width: 100%;
          margin: 0;
          border-right: #e5e5e5 1px solid;

          &.selection {
            flex: unset;
            width: 50px;
            font-size: 3rem;

            .half-checked {
              width: 2.5rem;
              height: 2.5rem;
              border-radius: .5rem;
              position: relative;
              background-color: #38C09E;

              .checkbox__inner-icon {
                position: absolute;
                opacity: 1;
                -webkit-transform: rotate(0deg);
                transform: rotate(0deg);
                height: 4px;
                top: 0;
                bottom: 0;
                margin: auto;
                left: 0px;
                right: 0px;
                bottom: 0;
                width: auto;
                border: none;
                border-radius: 4px;
                -webkit-transform: scale(0.5);
                transform: scale(0.5);
                background-color: #fff;
              }
            }
          }

          .label {
            width: 100%;
            height: 100%;
            overflow: hidden;
            white-space: nowrap;
            text-overflow: ellipsis;
            text-align: center;
            display: block;
          }

          &-contain {
            width: 100%;
            height: 100%;
            max-width: 20rem;
            overflow: hidden;
            text-align: center;
          }

          &:first-child {
            border-left: #e5e5e5 1px solid;
          }

          .input-box {
            // border: 1px solid #e5e5e5;
            min-height: 100%;
            font-size: 2.4rem;
            min-height: 5rem;
            display: flex;
            align-items: center;
            text-align: center;
            justify-content: center;

            .uni-easyinput {
              height: 100%;

              ::v-deep .uni-easyinput__content {
                height: 100%;

                .uni-input-wrapper {
                  font-size: 2.4rem;
                  line-height: 3rem;
                }

                .uni-easyinput__placeholder-class {
                  font-size: 2.4rem;
                  line-height: 3rem;
                }
              }
            }

            .input {
              outline: none !important;
              border: none !important;
              font-size: 2.4rem;
              height: 100%;
              width: 100%;
              display: flex;
              align-items: center;
              justify-content: center;
              text-align: center;
              // width: calc(100% - 4rem);
            }
          }
        }
      }
    }

    .to-more {
      text-align: right;
      padding: 1rem 0;
      display: flex;
      align-items: center;

      .line-orange {
        // color: #FFE8D1;
        color: #F3A250;

        // .text {
        //   color: #F3A250;
        // }
      }

      .line-cyan {
        color: #0BC99D;
      }

      .cu-btn {
        margin-left: 10rpx;
      }
    }
  }

  .child-form-wrap {
    // max-height: 70vh;
    // overflow-y: scroll;
    margin-top: 0px;
    min-width: 50rem;

    .bx-form-wrap {
      // padding-left: 10px;

      @media screen and(min-width:800px) {
        display: flex;
        flex-wrap: wrap;
      }
    }
  }

  .cu-dialog {
    width: auto;
  }

  .button-box {
    max-width: 500px;
    margin: 1rem 0;
    display: flex;
    justify-content: center;
    margin: 0 auto;
    padding: 20px 0 0;

    .button {
      min-width: 40%;
      margin-right: 2rem;

      &:last-child {
        margin-right: 0;
      }
    }
  }

  .child-form-wrap {
    ::v-deep .a-form {
      // .form-item {
      //   align-items: flex-start;
      //   .form-item-label {
      //     align-items: flex-start;
      //   }
      //   .form-item-content{
      //     align-items: flex-start;
      //   }
      // }
    }

    .custom-form {
      display: flex;
      flex-direction: column;
      min-height: 50vh;
      width: 30vw;

      .border {
        border: 1px solid #e5e5e5;
        background-color: #fff;
        border-radius: 4px;
        text-align: left;
        // padding-left: 10px;
      }

      .form-item {
        display: flex;
        align-items: center;
        margin-bottom: 1rem;

        .label {
          color: #333;
          min-width: 15rem;
          font-weight: bold;
          text-align: left;
        }

        .value {
          flex: 1;
        }
      }
    }
  }

  .close-btn {
    // border-radius: 10rem;
    display: flex;
    justify-content: space-between;
    align-items: center;

    .title {
      display: flex;
      padding: 0 2rem;
      font-size: 2.6rem;
      color: #333;
      // font-weight: bold;
    }

    .cu-btn {
      font-size: 3rem;
      font-weight: bold;
      height: 6rem;
      width: 6rem;
      // border-radius: 10rem;
    }

  }
</style>
